package com.yhq.oj.judge;

import cn.hutool.json.JSONUtil;
import com.yhq.oj.common.ErrorCode;
import com.yhq.oj.exception.BusinessException;
import com.yhq.oj.judge.sandbox.CodeSandBox;
import com.yhq.oj.judge.sandbox.CodeSandBoxFactory;
import com.yhq.oj.judge.sandbox.CodeSandBoxProxy;
import com.yhq.oj.judge.sandbox.model.ExcuteCodeRequest;
import com.yhq.oj.judge.sandbox.model.ExcuteCodeResponse;
import com.yhq.oj.judge.stratege.JudgeContext;
import com.yhq.oj.model.dto.question.JudgeCase;
import com.yhq.oj.judge.sandbox.model.JudgeInfo;
import com.yhq.oj.model.entity.Question;
import com.yhq.oj.model.entity.QuestionSubmit;
import com.yhq.oj.model.enums.JudgeInfoEnum;
import com.yhq.oj.model.enums.QuestionSubmitStatusEnum;
import com.yhq.oj.service.QuestionService;
import com.yhq.oj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @program: oj-backend
 * @description: 判题服务类
 * @author: HenryYang
 * @create: 2023-08-23 17:08
 **/
@Service
public class JudgeServiceImpl implements JudgeService {
    @Value("${codesandbox.type:example}")
    private String value;

    @Resource
    QuestionSubmitService questionSubmitService;
    @Resource
    QuestionService questionService;
    @Resource
    JudgeManager judgeManager;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "找不到提交信息");
        }
        // 1.获取题目提交以及题目信息
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        Integer status = questionSubmit.getStatus();
        Long questionId = questionSubmit.getQuestionId();

        if (questionId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        Question question = questionService.getById(questionId);
        String judgeCase = question.getJudgeCase();

        //2.判断题目状态是否合理，
        if (!Objects.equals(status, QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交状态异常");
        }
        if (Objects.equals(status, QuestionSubmitStatusEnum.RUNNING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "正在判题中，请勿重复提交");
        }
        //并修改题目提交状态
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        //3.调用代码沙箱，获取执行结果
        CodeSandBox codeSandBox = CodeSandBoxFactory.newInstance(value);
        codeSandBox = new CodeSandBoxProxy(codeSandBox);
        //为什么要用代理模式？因为代码沙箱的接口是不稳定的，可能会出现问题，所以需要一个代理类来处理异常
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCase, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExcuteCodeRequest excuteCodeRequest = ExcuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        // todo 如果编译失败，可以修改excuteCodeResponse中的message或者judgeInfo提示错误原因

        ExcuteCodeResponse excuteCodeResponse = codeSandBox.excuteCode(excuteCodeRequest);
        List<String> outputList = excuteCodeResponse.getOutputList();
        JudgeInfo judgeInfo = excuteCodeResponse.getJudgeInfo();
        if(excuteCodeResponse.getStatus()!= JudgeInfoEnum.SUCCESS.getCode()){ //不正常处理
            questionSubmitUpdate = new QuestionSubmit();
            questionSubmitUpdate.setId(questionSubmitId);
            questionSubmitUpdate.setStatus(excuteCodeResponse.getStatus());
            JudgeInfo errorJudgeInfo = new JudgeInfo();
            judgeInfo.setMessage(excuteCodeResponse.getMessage());
            questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(errorJudgeInfo));

        }else {
            //4.完善judgeContext，为doJudge做准备
            JudgeContext judgeContext = new JudgeContext();
            judgeContext.setJudgeInfo(judgeInfo);
            judgeContext.setInputList(inputList);
            judgeContext.setOutputList(outputList);
            judgeContext.setJudgeCaseList(judgeCaseList);
            judgeContext.setQuestion(question);
            judgeContext.setQuestionSubmit(questionSubmit);
            //5.根据执行结果，设置题目的判题状态和判题结果信息

            JudgeInfo judgeInfo1 = null;
            try {
                judgeInfo1 = judgeManager.doJudge(judgeContext);
            } catch (Exception e) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "判题时发生错误");
            }
            questionSubmitUpdate = new QuestionSubmit();
            questionSubmitUpdate.setId(questionSubmitId);
            questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.ACCEPTED.getValue());
            questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo1));
        }
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交更新失败");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);
        return questionSubmitResult;
    }
}